/*  
 * cafe-squarelegend.js
 * @Author :      GUORUI
 * @CreateDate :  2017年6月20日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	/**
	 * 创建控件界面
	 */
	function getNodeHtml(cfg){
		var wrapper = $('<div class="squarelegend '+ cfg.type + '">'),
			title = $('<div class="squarelegend-title">'),
			content = $('<div class="squarelegend-content">');
		title.append($('<span>').text(cfg.title));//.append($('<span class="squarelegend-close cafe-ifont cafe-ic-iconfontcha">'));
		var table = $('<table>');
		if(-1 != $.inArray(cfg.type,["zdz","zdz1","surface","high"])){
            wrapper.addClass("squarelegend-td-wind");
			if($.isEmptyObject(cfg.data) || cfg.data["WIND"]){
                wrapper.addClass("active");
			}else{
                wrapper.addClass("disabled");
			}
		}
		var tr = null;
		var num = "high" == cfg.type ? 2 : 3;
		var total = Math.ceil(tbObj[cfg.type].length / num) * num;
		for(var i = 0; i < total; i++){
			if(0 == i % num){
				tr = $('<tr>');
			}
			var td = $('<td>');
			td.addClass("disabled");
			tr.append(td);
			if(num - 1 == i % num){
				table.append(tr);
			}
		}
		content.append(table);
		wrapper.append(title).append(content);
		update(wrapper,cfg);
		return wrapper;
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
		$drop.undelegate().delegate(".squarelegend-content td:not(.statnm)>span","click",function(event){
			event.stopPropagation();
			if(!$(this).parent().hasClass("disabled")){
                var td = tbObj[cfg.type][$(this).parent().attr("index")];
                var proid = $.isEmptyObject(cfg.data) ? td.id : cfg.data[td.id].proid;
                var isActive = $(this).parent().hasClass("active");
				if(isActive){
					$(this).css("color","").text(td.name);
					$(this).parent().removeClass("active");
				}else{
					var pro = $(this).parent().data("pro");
					$(this).css("color",pro.color).text(pro.name);
					$(this).parent().addClass("active");
				}
                if("zdz" == cfg.type){
                    GIS.Station.eleShowControl(cfg.gisId,[0,1,2,3,4],[proid],isActive ? "hide" : "show");
                }else if("zdz1" == cfg.type){
                	var layerId;
                	if(proid.includes("WS")&&proid.includes("WD")){
                		layerId = "stationInfo_"+"wind"+proid.replace(",","&");
                	}else{
                		layerId = "stationInfo_"+proid;
                	}
                	GIS.Station.eleShowControl_single(cfg.gisId,layerId,isActive ? "hide" : "show");
                }else{
                    GIS.Element.singleShow(cfg.gisId,null,null,isActive ? "hide" : "show",proid,1,{id : cfg.layerId});
                }
			}
		}).delegate(".squarelegend-content td.statnm>span","click",function(event){//站点名显隐控制
            event.stopPropagation();
            if(!$(this).parent().hasClass("disabled")){
                var td = tbObj[cfg.type][$(this).parent().attr("index")];
                var isActive = $(this).parent().hasClass("active");
                if(isActive){
                    $(this).css("color","").text(td.name);
                    $(this).parent().removeClass("active");
                }else{
                    $(this).css("color","#7a7a7a").text(td.name);
                    $(this).parent().addClass("active");
                }
                GIS.Station.eleControl(cfg.gisId,[0,1,2,3,4],$(this).parent().data("eleids"),isActive ? "hide" : "show",'Name');
            }
        }).delegate(".squarelegend-content .squarelegend-td-wind","click",function(){
			if(!$(this).hasClass("disabled")){
				if($(this).hasClass("active")){
					$(this).removeClass("active");
				}else{
					$(this).addClass("active");
				}
			}
		}).delegate(".squarelegend-title","mousedown",function(event){
			event.stopPropagation();
			event.preventDefault();
			var isMove = true;
			var _this = $(this).closest(".squarelegend").parent();
			if("static" == _this.css("position")){
				_this = _this.parent();
			}
			var m_x = parseInt(_this.css("right"));//点击窗体时，left
			var m_y = parseInt(_this.css("bottom"));//点击窗体时，top
			var abs_x = event.pageX;//点击窗体时，左边距
			var abs_y = event.pageY;//点击窗体时，上边距
			//单击住头部可进行拖拽，计算移动大小，以及移动范围限制
			$(document).unbind('mousemove').bind('mousemove',function(event){
				if(isMove) {
					//event.pageX,移动后的左边距;event.pageY,移动后的上边距
					var ebs_x = m_x - (event.pageX - abs_x); //移动后的left
					var ebs_y = m_y - (event.pageY - abs_y);//移动后的top
					
					var body_w = $(".cafe-container").width();
					var body_h = $(".cafe-container").height();
					var div_w = _this.width();
					var div_h = _this.height();
					//不可超出左右边框
					if(ebs_x <= 0) {
						ebs_x = 0;
					}else if (ebs_x > body_w - div_w) {
						ebs_x = body_w - div_w;
					}
					//不可超出上下边框
					if(ebs_y <= 0) {
						ebs_y = 0;
					} else if (ebs_y > body_h - div_h) {
						ebs_y = body_h - div_h;
					} else {
						
					}
					//重新设定弹出框的左边距，上边距
					_this.css({'right':ebs_x,'bottom':ebs_y});
				}
			}).mouseup(function(){
				isMove = false;
				$(document).off('mousemove');
			});//鼠标移除事件；单击事件结束事件。
		});
	}
	/**
	 * 更新九宫格
	 */
	function update($drop,cfg){
		$.each(tbObj[cfg.type],function(i,obj){
			var tdObj = $.isEmptyObject(cfg.data) ? obj : cfg.data[obj.id];
			var $td = $drop.find("td:eq("+i+")");
            if(0 == $td.find("span").length || "statnm" != obj.id) {
                $td.attr("index", i).removeClass("active").empty();
                if (tdObj && tdObj.color) {
                    var title = tdObj.title || tdObj.name;
                    var name = tdObj.name || obj.name;
                    $td.attr("tid", obj.id).removeClass("disabled").addClass("active")
                        .append($('<span>').css({"color": tdObj.color}).attr("title", title).text(name)).data("pro", tdObj);
                } else {
                    $td.addClass("disabled").append($('<span>').text(obj.name));
                }
            }
		});
		if("zdz" == cfg.type){
			var eleids = [];
            $drop.find("td:not(:last):not(.disabled)").each(function(){
                eleids.push($(this).data("pro").proid);
			});
            var $statnm = $drop.find("td:last");
            if(eleids.length > 0){
                $statnm.removeClass("disabled").addClass("statnm").data("eleids",eleids);
			}else{
                $statnm.removeClass("active statnm").addClass("disabled").find("span").css("color","");
			}
		}
	}
	var tbObj = {
			zdz : [
				{id:"RH",name:"湿度"},
				{id:"",name:""},
				{id:"SP",name:"气压"},
				{id:"TMP",name:"气温"},
				{id:"WIND",name:"风"},
				{id:"TP",name:"降水"},
				{id:"VIS",name:"能见度"},
				{id:"",name:""},
				//{id:"statnm",name:"站名"}
			],
        	surface : [
                {id:"",name:""},
                {id:"hcs",color:"#fe7f0e",title:"高云状",name:"CH"},
                {id:"spv24h",color:"#0386ea",title:"24小时变压",name:"P24P24"},
                {id:"t",color:"#12c060",title:"温度",name:"TTT"},
                {id:"mcs",color:"#be2eb5",title:"中云状",name:"CM"},
                {id:"sp",color:"#7833f0",title:"海平面气压",name:"PPPP"},
                {id:"wp",color:"#be960a",title:"现在天气",name:"WW"},
                {id:"tcc,wind",color:"#1f201f",title:"总云量",name:"N"},
                {id:"spv3h",color:"#da0a09",title:"3小时变压",name:"PPPa"},
                {id:"vis",color:"#2728fb",title:"能见度",name:"VV"},
                {id:"lcs,lcc",color:"#7fa5c8",title:"低云状、低云量",name:"CLNh"},
                {id:"pwp1,pwp2",color:"#25b014",title:"过去天气",name:"W1W2"},
                {id:"dpt",color:"#3a9b00",title:"露点",name:"TdTdTd"},
                {id:"lch",color:"#001e0e",title:"低云高",name:"h"},
                {id:"RR",color:"#f089ad",title:"降水量",name:"RRR"}
			],
            high : [
                {id:"t",color:"#ff0000",title:"温度",name:"TT"},
                {id:"height",color:"#969600",title:"高度",name:"HHH"},
                {id:"dpt",color:"#1d40f7",title:"温度露点差",name:"DD"},
                {id:"",name:""}
			]

	};
	var CFSquarelegend = function(settings){
		var options = {
			appendTo: '',//控件所在容器
			gisId : null,//GIS地图id
			layerId : null,//GIS图层Id
			title : "",  //图例标题
			type : null,  //图例类型 自动站：zdz；
			data : {}
		};
		this.config = $.extend({},options, settings);
		this.$drop = getNodeHtml(this.config);
		_eves(this.$drop,this.config);
		if(this.config.appendTo){
            $(this.config.appendTo).find(".squarelegend."+this.config.type).remove();
			$(this.config.appendTo).append(this.$drop);
		}
	}
	
	CFSquarelegend.prototype = {
		show : function(){
			this.$drop.parent().show();
		},
		hide : function(){
			this.$drop.parent().hide();
		},
		remove : function(type,delFun){
			if(type){
				$(this.config.appendTo).find(".squarelegend."+type).remove();
                if(this.$drop.siblings().is(":hidden") && $.isFunction(delFun)){
                    delFun();
                }
			}else{
                this.$drop.remove();
			}
		},
		init : function(data){
			this.$drop.show();
			this.config.data = data ? data : {};
			update(this.$drop,this.config);
		},
		update : function(type,newObj){
			this.$drop.show();
			this.config.data[type] = newObj;
			update(this.$drop,this.config);
		},
		del : function(type, delFun){
			delete this.config.data[type];
			update(this.$drop,this.config);
			if($.isEmptyObject(this.config.data)){
				this.$drop.hide();
				if(!this.$drop.siblings().is(":visible") && $.isFunction(delFun)){
					delFun();
				}
			}
		},
		isActiveByProid : function (cid) {
            return this.$drop.find("td[tid='"+cid+"']").hasClass("active");
        }
	};
	
	CafeJS.Squarelegend = function(settings){
		var drop =new CFSquarelegend(settings);
		return drop;
	}
});